package music

import (
	"dustbe/database"
	"dustbe/util"
	"fmt"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
)

type DeletePackage struct {
	StaffId int `json:"staffId"`
}

func DeleteStaff(c *gin.Context) {
	ok := util.LimitIpInterval(c, 5)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "删除过于频繁"})
		return
	}

	var deletePackage DeletePackage
	if c.ShouldBindJSON(&deletePackage) != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "请求体格式错误"})
		return
	}

	staffId := deletePackage.StaffId
	user, err := database.FindStaffPublisherByStaffId(staffId)
	if err != nil {
		fmt.Println(err.Error())
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}

	err = database.DeleteStaff(int64(staffId))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "数据库删除失败"})
		return
	}

	publisherId := user.Id
	err = checkPrivilegeByPublisherId(c, int(publisherId))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}

	staffPath := fmt.Sprintf("%s/%d-%d.json", staffRoot, publisherId, staffId)

	staffPathExist, _ := util.CheckFilePath(staffPath)
	if staffPathExist {
		err := os.Remove(staffPath)
		if err != nil {
			fmt.Println(err.Error())
			c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "删除失败（删除本地文件失败）"})
			return
		}
	}

	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : "删除成功"})
}